package com.dsh.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dsh.common.response.ResultObject;
import com.dsh.mapper.UserMapper;
import com.dsh.model.UserEntity;
import com.dsh.model.UserLogin;
import com.dsh.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    RedisTemplate redisTemplate;

    public ResultObject<Map> userLogin(UserLogin u) {
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(UserEntity::getUsername,u.getUname());
        List<UserEntity> list = userMapper.selectList(wrapper);
        if (list.size()>0){
            UserEntity userEntity = list.get(0);
            if (u.getUpwd().equals(userEntity.getPassword())){
                //(1)校验账号密码是否正确，并生成jwt令牌
                String token = JwtUtils.createToken(userEntity.getId().toString(), userEntity.getUsername(), null);
                String username = userEntity.getUsername();

                Map map=new HashMap();
                map.put("token",token);
                map.put("username",username);

                //(2)利用Redis实现令牌有效期2分钟，若2分钟内有操作则自动续期
                redisTemplate.opsForValue().set("login_token_"+userEntity.getId(),token,2, TimeUnit.MINUTES);

                return new ResultObject<>(true,"1","登录成功",map);
            }else {
                return new ResultObject<>(false,"0","密码错误",null);
            }
        }else {
            return new ResultObject<>(false,"0","用户不存在",null);
        }
    }
}
